<template>
  <page-wrap
    ref="pageWrap"
    hideTab
    back
    :title="title"
    :show-top="showTop"
    :dark="loaded ? false : true"
    :hideSafeArea="true"
    :bg-color="dynamicColor"
  >
    <view class="wrapper" :style="'padding-top:' + navHeight + 'px;'">
      <view class="header">
        <image :src="campusMatchDetail.icon" class="logo"></image>
        <view class="title-box">
          <view class="title">{{ campusMatchDetail.name }}</view>
          <view class="tags">
            <text class="tag" v-for="(item, index) in tags" :key="index">{{
              item
            }}</text>
          </view>
        </view>
      </view>
      <view class="combinatorial-info">
        <view class="left">
          <view class="up">
            <text class="combinatorial-name"
              >选科组合: {{ currentSubject }}</text
            >
            <view class="change-btn" @click="handleChangeSubject">
              <image :src="edit" class="edit-img"></image>
              <text class="text">更换</text>
            </view>
          </view>
          <view class="down">
            匹配专业
            <text class="num">
              {{ campusMatchDetail.professionNum || '-' }} </text
            >个
          </view>
        </view>
        <view class="right" v-if="personId">
          <view class="progress-box"> </view>
          <u-circle-progress
            active-color="#FF7E65"
            inactive-color="#ececec"
            :percent="campusMatchDetail.matchRateNum"
            width="120"
            border-width="8"
            bg-color="transparent"
          >
            <view class="u-progress-content">
              <text class="u-progress-info">{{
                campusMatchDetail.matchRate || '-'
              }}</text>
            </view>
          </u-circle-progress>
          <view class="text">专业匹配率</view>
        </view>
      </view>
      <view v-if="loading" class="loading-box">
        <u-loading v-if="loading" mode="flower" size="42"></u-loading>
      </view>
      <view v-else class="table-box">
        <u-table
          v-if="tableData.length > 0"
          bg-color="#fff"
          border-color="#efefef"
          padding="16rpx"
          font-size="24rpx"
          align="left"
          :th-style="{
            textAlign: 'center',
            color: '#D8D8D8',
            backgroundColor: '#fff',
          }"
          color="#222"
        >
          <!-- 表格头 -->
          <u-tr class="u-tr">
            <u-th
              class="u-th"
              v-for="(item, index) in tableHeaderData"
              :key="index"
              >{{ item.name }}</u-th
            >
          </u-tr>
          <!-- 表格体 -->
          <u-tr class="u-tr" v-for="(item, index) in tableData" :key="index">
            <u-td class="u-th" v-for="(_item, _index) in item" :key="_index">
              <view v-if="_item.isSubjectName">{{ _item.name }}</view>
              <view v-else>
                <template v-if="_item.name === '10'">无限制</template>
                <template v-else>
                  <view
                    >首选：<text
                      :class="[
                        _item.subjectNames.includes('物理') ? 'highlight' : '',
                      ]"
                      >物理</text
                    >/<text
                      :class="[
                        _item.subjectNames.includes('历史') ? 'highlight' : '',
                      ]"
                      >历史</text
                    ></view
                  >
                  <view>再选：{{ _item.subjectNamesSecond.join('、') }}</view>
                </template>
              </view>
            </u-td>
          </u-tr>
        </u-table>
        <view class="main-content-empty" v-else>
          <Empty
            :baseImg="emptyImg"
            text="暂无数据"
            textColor="#888"
            :fontWeight="400"
          />
        </view>
      </view>
    </view>
    <u-popup v-model="showChooseSubjectPopup" mode="bottom" border-radius="14">
      <view class="choose-subject">
        <view class="choose-title">
          <view class="left">首选</view>
          <view class="right">选择一门学科</view>
        </view>
        <view class="choose-box">
          <view
            :class="
              item.id == currentFirstSubject.id
                ? 'choose-box-item-selected'
                : 'choose-box-item'
            "
            v-for="(item, index) in firstSubject"
            :key="index"
            @click="selectFirstSubject(item)"
            >{{ item.name }}
          </view>
        </view>
        <view class="choose-title">
          <view class="left">再选</view>
          <view class="right">选择二门学科</view>
        </view>
        <view class="choose-box">
          <view
            :class="
              currentSecondSubjectList.includes(item)
                ? 'choose-box-item-selected'
                : 'choose-box-item'
            "
            v-for="(item, index) in secondSubject"
            :key="index"
            @click="selectSecondSubject(item)"
            >{{ item.name }}
          </view>
        </view>
        <view class="search-btn" @click="changeData">确定</view>
      </view>
    </u-popup>
    <LoginDialog
      ref="loginDialog"
      @loginSuccessBack="loginSuccessBack"
    ></LoginDialog>
  </page-wrap>
</template>

<script>
import Empty from '@/components/Empty.vue';
import { cardRegist } from '@/api/modules/career';
import ShareMixin from '@/mixins/share';
import LoginDialog from '@/components/LoginDialog';
import { getCollegeInfoAndList } from '@/api/modules/gk';
const classMap = new Map();
classMap.set('10', '不限');
classMap.set('11', '物理');
classMap.set('12', '历史');
classMap.set('13', '生物');
classMap.set('14', '化学');
classMap.set('15', '政治');
classMap.set('16', '地理');
export default {
  mixins: [ShareMixin],
  components: {
    Empty,
    LoginDialog,
  },
  data() {
    return {
      personId: '',
      shareTitle: '震惊！同分数段的同学，靠选科组合提前锁定百万年薪赛道',
      sharePath:
        '/pagesSub/nationalCollegeEntranceExamination/campusMatchDetail/index',
      imageUrl:
        'https://img3.job1001.com/ypMp/elan/images/subjectSelect/subjectSelectSharePic.png',
      navHeight: getApp().globalData.navHeight,
      title: '院校匹配详情',
      edit: 'https://img3.job1001.com/ypMp/elan/images/saas/edit.png',
      emptyImg: this.$imgBaseSelf + 'common/empty.png',
      loading: false,
      showTop: false,
      showChooseSubjectPopup: false,
      dynamicColor: 'transparent',
      campusMatchDetail: {},
      currentSubject: '历史、政治、地理',
      firstSubject: [
        {
          name: '物理',
          id: '11',
        },
        {
          name: '历史',
          id: '12',
        },
      ],
      secondSubject: [
        {
          name: '化学',
          id: '14',
        },
        {
          name: '生物',
          id: '13',
        },
        {
          name: '政治',
          id: '15',
        },
        {
          name: '地理',
          id: '16',
        },
      ],
      tableHeaderData: [{ name: '专业名' }, { name: '选科' }],
      tableData: [
        // [
        //   { name: '文科试验班类(哲学(等各专业))(新雅书院)' },
        //   { name: '首选:物理/历史 <br/>再选:不限' }
        // ],
      ],
      currentFirstSubject: {}, // 当前选中的必须按科目
      currentSecondSubjectList: [], // 选择两个科目的数据
      selectedSubjectList: [], // 全部选择的科目列表
      tags: [],
      collegeId: '',
      subjectCombination: '', // 逗号分隔的id，
      currentSubject: '', // 顿号分隔的名称
    };
  },
  onPageScroll(e) {
    //滚动改变颜色
    this.showTop = e.scrollTop >= 60;
    if (this.showTop) {
      this.dynamicColor = '#cfe8fd';
      this.title = this.campusMatchDetail.name;
    } else {
      this.dynamicColor = 'transparent';
      this.title = '院校匹配详情';
    }
  },
  onLoad(opt) {
    this.collegeId = opt.collegeId;
    this.subjectCombination = opt.subjectCombination;
    this.currentSubject = opt.currentSubject;
    this.getCollegeInfoAndListFn();
    this.imageUrl =
      'https://img3.job1001.com/ypMp/elan/images/subjectSelect/subjectSelectSharePic.png'; //必须重新赋值
    this.sharePath = `/pagesSub/nationalCollegeEntranceExamination/campusMatchDetail/index?collegeId=${this.collegeId}&subjectCombination=${this.subjectCombination}&currentSubject=${this.currentSubject}`;
    if (!this.personId) {
      this.$refs.loginDialog.setVisibility(true);
      return;
    }
  },
  methods: {
    async cardRegistFn() {
      const params = {
        personId: this.personId,
        force: 1,
      };
      params.cardType = 143;
      const res = await cardRegist(params);
      return res;
    },
    loginSuccessBack() {
      //TODO:登录成功后触发埋点
      this.personId = uni.getStorageSync('person-id').slice(2);
      this.cardRegistFn();
    },
    async getCollegeInfoAndListFn() {
      this.loading = true;
      const params = {
        collegeId: this.collegeId,
        subjectCombination: this.subjectCombination,
      };
      try {
        const res = await getCollegeInfoAndList(params);
        this.loading = false;
        if (res.code == 200) {
          this.campusMatchDetail = res.data;
          this.campusMatchDetail.matchRateNum =
            +this.campusMatchDetail.matchRate;
          this.getTags();
          this.getProfessionList();
        }
      } catch (error) {
        this.loading = false;
      }
    },
    getProfessionList() {
      const { professionList } = this.campusMatchDetail;
      const tempTableData = this.flattenAndConcatenate(professionList);
      // tableData是一个二维数组
      this.tableData = this.convertToTwoDimensionalArray(tempTableData);
    },
    // 数组转为二维数组
    convertToTwoDimensionalArray(array) {
      let twoDimensionalArray = [];
      for (let i = 0; i < array.length; i += 2) {
        // 检查是否有下一个元素，避免数组长度为奇数时出现undefined的情况
        if (i + 1 < array.length) {
          twoDimensionalArray.push([array[i], array[i + 1]]);
        } else {
          // 如果是最后一个元素且没有成对的元素，则单独作为一个子数组
          twoDimensionalArray.push([array[i]]);
        }
      }
      return twoDimensionalArray;
    },
    // 展平数组并拼接名称
    flattenAndConcatenate(professions) {
      let result = [];
      professions.forEach((profession) => {
        const subjectIds = profession.limitSubject.split(',');
        const subjectNames = subjectIds.map((item) => classMap.get(item));
        const subjectNamesSecond = subjectNames.filter((item) => {
          return item != '物理' && item != '历史';
        });
        if (profession.children && profession.children.length > 0) {
          // 提取子元素的 cpName 并拼接
          const cpNames = profession.children
            .map((child) => child.cpName)
            .join('，');
          result.push({
            name: `${profession.cpName}（${cpNames}）`,
            isSubjectName: true,
          });
          result.push({
            name: profession.limitSubject,
            subjectNames,
            subjectNamesSecond,
          });
        } else {
          result.push({
            name: profession.cpName,
            isSubjectName: true,
          });
          result.push({
            name: profession.limitSubject,
            subjectNames,
            subjectNamesSecond,
          });
        }
      });
      return result;
    },
    getTags() {
      const { collegeType, dualClassName, levelName, natureName } =
        this.campusMatchDetail;
      const fields = [collegeType, dualClassName, levelName, natureName];

      this.tags = fields.reduce((temp, field) => {
        if (field) {
          // temp.push(...field.split(","));
          temp.push(field);
        }
        return temp;
      }, []);

      const resultArray = [];

      this.tags.forEach((item) => {
        if (item.includes(',')) {
          // 如果包含逗号，则按逗号分割并展开
          resultArray.push(...item.split(','));
        } else {
          // 如果不包含逗号，直接添加到结果数组
          resultArray.push(item);
        }
      });

      this.tags = resultArray;
      console.log('tags', this.tags);
    },
    selectFirstSubject(item) {
      this.currentFirstSubject = item;
    },
    selectSecondSubject(item) {
      if (this.currentSecondSubjectList.includes(item)) {
        return;
      } else {
        this.currentSecondSubjectList.push(item);
        if (this.currentSecondSubjectList.length > 2) {
          this.currentSecondSubjectList.shift();
        }
      }
    },
    changeData() {
      if (
        this.currentSecondSubjectList.length == 2 &&
        this.currentFirstSubject.id
      ) {
        this.selectedSubjectList = [
          this.currentFirstSubject,
          ...this.currentSecondSubjectList,
        ];
        this.currentSubject = this.selectedSubjectList
          .map((item) => item.name)
          .join('、');
        this.subjectCombination = this.selectedSubjectList
          .map((item) => item.id)
          .join(',');
        this.showChooseSubjectPopup = false;
        this.getCollegeInfoAndListFn();
      }
    },
    handleChangeSubject() {
      this.showChooseSubjectPopup = true;
    },
  },
};
</script>

<style lang="scss" scoped>
$img-base-person: $img-base + 'careerPath/';
::v-deep .u-th {
  line-height: 48rpx;
}
.wrapper {
  min-height: 100vh;
  background-image: url($img-base + 'careerPath/majorDetailBg.png');
  background-size: 100% 832rpx;
  background-repeat: no-repeat;
  padding: 0 32rpx;
  position: relative;
  .header {
    display: flex;
    align-items: center;
    margin-top: 42rpx;
    .logo {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
    }
    .title-box {
      margin-left: 24rpx;
      .title {
        font-weight: bold;
        font-size: 40rpx;
        color: #222222;
        margin-bottom: 12rpx;
      }
      .tags {
        display: flex;
        flex-wrap: wrap; /* 允许换行 */
        gap: 8rpx; /* 为子元素添加间距 */
        .tag {
          // margin-right: 8rpx;
          font-size: 24rpx;
          color: #1a69ff;
          padding: 2rpx 16rpx;
          font-size: 24rpx;
          border: 2rpx solid #1a69ff;
          border-radius: 4rpx;
        }
      }
    }
  }
  .combinatorial-info {
    display: flex;
    justify-content: space-between;
    .left {
      margin-top: 70rpx;
      .title-box {
        display: flex;
        align-items: center;
        .title {
          font-weight: bold;
          font-size: 40rpx;
          color: #222222;
        }
        .sub-title {
          font-size: 28rpx;
          color: #52586d;
          margin-left: 26rpx;
          display: flex;
          align-items: center;
          .name {
            margin-right: 16rpx;
          }
        }
      }
      .up {
        display: flex;
        align-items: center;
        .combinatorial-name {
          margin-right: 20rpx;
        }
        .change-btn {
          display: flex;
          align-items: center;
          .edit-img {
            width: 32rpx;
            height: 32rpx;
          }
          .text {
            font-size: 26rpx;
            color: #109eeb;
            margin-left: 8rpx;
          }
        }
      }
      .down {
        margin-top: 18rpx;
        color: #555;
        font-size: 26rpx;
        .num {
          font-weight: bold;
          color: #f56246;
          padding: 0 6rpx;
        }
      }
    }
    .right {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 34rpx;
      position: relative;
      .progress-box {
        position: absolute;
        width: 110rpx;
        height: 110rpx;
        background-color: #fff;
        border-radius: 50%;
        top: 4rpx;
      }
      ::v-deep .u-circle-progress {
        border-radius: 50%;
      }
      .u-progress-content {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .u-progress-info {
        font-family: D-DIN-PRO, D-DIN-PRO;
        font-weight: bold;
        font-size: 26rpx;
        color: #333333;
      }
      .text {
        margin-top: 12rpx;
        font-size: 24rpx;
        color: #222222;
        font-weight: bold;
      }
    }
  }
  .loading-box {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40vh;
  }
  .table-box {
    margin: 50rpx 0 80rpx 0;
    min-height: 100rpx;
    .highlight {
      // color: #f75a3e;
    }
  }
}
.choose-subject {
  height: 578rpx;
  background: #ffffff;
  border-radius: 10rpx;
  margin-top: 46rpx;
  padding: 24rpx;
  .choose-title {
    display: flex;
    flex-direction: row;
    align-items: flex-end;
    .left {
      height: 42rpx;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 30rpx;
      color: #222222;
      line-height: 42rpx;
    }
    .right {
      height: 36rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 26rpx;
      color: #999999;
      line-height: 36rpx;
      margin-left: 24rpx;
    }
  }
  .choose-box {
    margin: 28rpx 0 40rpx 0;
    display: flex;
    align-items: center;
    .choose-box-item,
    .choose-box-item-selected {
      width: 146rpx;
      height: 72rpx;
      border-radius: 8rpx;
      margin-right: 16rpx;
      font-size: 28rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
    }
    .choose-box-item {
      border: 2rpx solid #d9d9d9;
      color: #333333;
    }
    .choose-box-item-selected {
      border: 2rpx solid #f75a3e;
      color: #f75a3e;
    }
  }
  .show-data {
    height: 78rpx;
    background: #f5fbff;
    border-radius: 8rpx 8rpx 0rpx 0rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    .blue-column {
      width: 2rpx;
      height: 38rpx;
      border: 2rpx solid #b6d5e8;
      margin: 0 30rpx;
      background-color: #b6d5e8;
    }
    .left-data {
      color: #4079a8;
      font-size: 24rpx;
      span {
        margin-left: 8rpx;
        font-size: 28rpx;
        color: #ff8c00;
      }
    }
    .right-data {
      color: #4079a8;
      font-size: 24rpx;
      span {
        margin-left: 8rpx;
        font-size: 28rpx;
        color: #00ac51;
      }
    }
  }
  .search-btn {
    height: 80rpx;
    background: #f75a3e;
    border-radius: 8rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 30rpx;
    color: #ffffff;
  }
}
</style>
